/* eslint-disable default-case */
import React from 'react';
import { message, Row, Modal } from 'antd';
import {
  getDetail,
  getInsInfor,
  updateInsData,
  getSingleData,
  getDictData,
  getSuppList,
  getDictList,
  getAddEmpAccuList,
  getAddEmpAccuProList,
  changeArea,
  bigApply,
  singleApply,
  onLineDecl,
  offBigApply,
  offSingleApply,
  underLineDecl,
  signProcanel,
  handleOkPro,
  handleOkSuc,
  handleOkFail,
  cancleApply,
  remarkOk,
  getDeclList,
  getProgress,
  cancelProbFlag,
  insertProbFdbk,
  problemGet,
  getRemarkData,
  addRemarkData,
  bmUploadFile,
  pUploadFile,
} from '@/services/addempaccu';
import { getUploadProgress } from '@/services/careermange';
import * as service from '@/services/socket';
import downloadFile from '@/utils/utils';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';

const namespace = 'addempaccu';

let typeName;

export default {
  namespace,
  state: {
    batchQuery: {
      // // 批量上传数据
      areaId: null,
      contType: null,
      progressPercent: 0,
    },
    copyAll: {},
    downParam: {},
    declDetailIds: [], // 申报明细表选中的数据
    proFormFieldsValue: {},
    // 办理备注
    textR: '',
    result: [],
    detail: {
      sendInfoDetDto: {},
      persion: {},
      mkupPayDets: [],
      accuOrdYmDets: [],
      accuRemarks: [],
      matSubs: [],
    },
    insData: [],
    remarkData: [],
    singleInfo: {},
    dictData: { addDetInfoList: [{ suppAccuAccos: [] }], addTypes: [], joinDtos: [] },
    formFieldsValue: {},
    flag: false,
    expandForm: false,
    activeKey: '1',
    tabList: [
      { itemCode: '1', itemName: '待申报' },
      { itemCode: '2', itemName: '申报中' },
      { itemCode: '3', itemName: '已申报' },
      // { itemCode: '4', itemName: '申报失败' },
      { itemCode: '5', itemName: '问题人员' },
      { itemCode: '6', itemName: '已取消' },
    ],
    pageData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    defaultLibrary: null,
    execStateList: [],
    payWayList: [],
    curMthDeclFlagList: [],
    matStateList: [],
    declWayList: [],
    declData: {
      data: {
        optDetailsNum: 20,
        pageRecords: [],
        totalCount: 1,
      },
      success: false,
    },
    progressPercent: 0,
    proInfo: {},
    probFbdks: [],
    addDetId: '',
    resultInfo: {
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batNo: '', // 批次号
      errorParams: null, // 下载错误数据参数
    },
    showProgress: false,
    currentStep: 0,
    tag: '',
  },

  effects: {
    *getUploadProgress({ payload, callback }, { call, put }) {
      const response = yield call(getUploadProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateQuery',
          payload: { progressPercent: response.data.successProp },
        });
      }
      if (callback && typeof callback === 'function') {
        callback(response);
      }
    },
    *getProgress({ payload }, { call, put }) {
      const res = yield call(getProgress, payload);
      if (res.success) {
        yield put({
          type: 'updateModelData',
          payload: {
            progressPercent: res.data.successProp,
          },
        });
      } else {
        message.warning(`${res.message || '查询失败'}`);
      }
      return res;
    },
    *getDeclList({ payload }, { call, put }) {
      const res = yield call(getDeclList, payload);
      if (res) {
        yield put({
          type: 'updateDeclList',
          payload: res,
        });
      }
      return res;
    },
    *remarkOk({ payload }, { call }) {
      const res = yield call(remarkOk, payload);
      if (!res.success === true) {
        message.warning(res.message || '服务端错误');
      }
      return res;
    },
    *cancleApply({ payload }, { call }) {
      const res = yield call(cancleApply, payload);
      if (res.success === true) {
        message.success('操作成功！');
      } else {
        message.warning(res.message || '服务端错误');
      }
      return res;
    },
    *handleOkFail({ payload }, { call }) {
      const res = yield call(handleOkFail, payload);
      if (!res.success === true) {
        message.warning(res.message || '服务端错误');
      }
      return res;
    },
    *handleOkSuc({ payload }, { call }) {
      const res = yield call(handleOkSuc, payload);
      return res;
    },
    *handleOkPro({ payload }, { call }) {
      const res = yield call(handleOkPro, payload);
      if (res.success) {
        if (String(res.rspCode) === '201') {
          message.warning(res.message || '服务端错误');
        } else {
          message.success('标记成功！');
        }
      }
      return res;
    },
    *signProcanel({ payload }, { call }) {
      const res = yield call(signProcanel, payload);
      if (res.success === true) {
        message.success('取消成功');
      } else {
        message.warning(res.message || '服务端错误');
      }
      return res;
    },
    *underLineDecl({ payload }, { call, put }) {
      const response = yield call(underLineDecl, payload);
      yield put({
        type: 'updateModelData',
        payload: {
          batchId: response.data.batchId,
          tag: 'underline',
        },
      });
      if (response.success) {
        if (response.data && response.data.successProp !== 100 && !response.data.declErrMessage) {
          typeName = 'index';
          yield put({
            type: 'updateModelData',
            payload: {
              showProgress: true,
              tag: 'underline',
            },
          });
          // yield call(service.socketChannel, {
          //   type: 'sub',
          //   data: { to: response.data && (response.data.batchId || response.data), type: 'task' },
          // });

          const { batchId } = response.data;
          const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

          yield put.resolve({
            type: `socket/${SocketActions.subSocketChannel}`,
            payload: {
              batchTask,
            },
          });
        } else {
          yield put({
            type: 'updateIndexBatchTask',
            payload: response.data,
          });
        }
      } else {
        // 上传失败
        message.warning(`${response.message || '操作失败：服务端错误'}`);
      }
      return response;
    },
    // 匹配唯一batchId
    *matchBatchId({ payload }, { put, select }) {
      const { batchId } = yield select(state => state.addempaccu);
      if (batchId === payload.batchId) {
        yield put({
          type: 'updateIndexBatchTask',
          payload,
        });
      }
    },
    *offSingleApply({ payload }, { call }) {
      const res = yield call(offSingleApply, payload);
      return res;
    },
    *offBigApply({ payload }, { call }) {
      const res = yield call(offBigApply, payload);
      return res;
    },
    *onLineDecl({ payload }, { call, put }) {
      const response = yield call(onLineDecl, payload);
      yield put({
        type: 'updateModelData',
        payload: {
          batchId: response.data.batchId,
          tag: 'online',
        },
      });
      if (response.success) {
        if (response.data && response.data.successProp !== 100 && !response.data.declErrMessage) {
          typeName = 'index';
          yield put({
            type: 'updateModelData',
            payload: {
              showProgress: true,
            },
          });
          // yield call(service.socketChannel, {
          //   type: 'sub',
          //   data: { to: response.data && (response.data.batchId || response.data), type: 'task' },
          // });

          const { batchId } = response.data;
          const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

          yield put.resolve({
            type: `socket/${SocketActions.subSocketChannel}`,
            payload: {
              batchTask,
            },
          });
        } else {
          yield put({
            type: 'updateIndexBatchTask',
            payload: response.data,
          });
        }
      } else {
        // 上传失败
        message.warning(`${response.message || '操作失败：服务端错误'}`);
      }
      return response;
    },
    *singleApply({ payload }, { call }) {
      const res = yield call(singleApply, payload);
      return res;
    },
    *changeArea({ payload }, { call, put }) {
      const res = yield call(changeArea, payload);
      if (res.success && res.data) {
        yield put({
          type: 'updateArea',
          payload: res.data,
        });
      } else if (!res.success) {
        message.warning(res.message || '服务端错误');
      }
      return res;
    },
    *bigApply({ payload }, { call }) {
      const res = yield call(bigApply, payload);
      return res;
    },
    *getInfor({ payload }, { call, put }) {
      const res = yield call(getDetail, payload);
      if (res.success) {
        yield put({
          type: 'getDetail',
          payload: {
            data: res.data,
          },
        });
      } else {
        message.warning(res.message);
      }
    },
    *getDict({ payload }, { call, put }) {
      const res = yield call(getDictData, payload);
      if (res.success) {
        yield put({
          type: 'getDictData',
          payload: {
            data: res.data,
          },
        });
      } else {
        message.warning(res.message);
      }
    },
    *getIns({ payload }, { call, put }) {
      const res = yield call(getInsInfor, payload);
      if (res.success) {
        yield put({
          type: 'getInsInfor',
          payload: {
            data: res.data,
          },
        });
      } else {
        message.warning(res.message);
      }
    },
    *updateIns({ payload, callback }, { call, select, put }) {
      const vno = yield select(state => state.addempaccu.insData.vno);
      const sendId = yield select(state => state.addempaccu.detail.persion.sendId);
      const busiId = yield select(state => state.addempaccu.detail.persion.accuEmpOrdId);
      const accuEmpOrdId = yield select(state => state.addempaccu.insData.accuEmpOrdId);
      const res = yield call(updateInsData, { ...payload, accuEmpOrdId, vno });
      if (res.success) {
        callback(true);
        const resAgin = yield call(getInsInfor, { addDetId: payload.addDetId });
        if (resAgin.success) {
          yield put({
            type: 'updateData',
            payload: resAgin.data,
          });
        } else {
          message.warning(res.message);
        }
        const resAginData = yield call(getRemarkData, { sendId, busiId });
        if (resAgin.success) {
          yield put({
            type: 'remarkData',
            payload: resAginData.data,
          });
        } else {
          message.warning(res.message);
        }
      } else {
        message.warning(res.message);
      }
    },
    // 获取备注
    *getRemark({ payload }, { call, put }) {
      const res = yield call(getRemarkData, payload);
      if (res.success) {
        yield put({
          type: 'getRemarkData',
          payload: {
            data: res.data,
          },
        });
      } else {
        message.warning(res.message);
      }
    },
    *addHdlRemark({ payload, callback }, { call, select, put }) {
      const sendId = yield select(state => state.addempaccu.detail.persion.sendId);
      const taskId = yield select(state => state.addempaccu.detail.persion.taskId);
      const busiId = yield select(state => state.addempaccu.detail.persion.accuEmpOrdId);
      const res = yield call(addRemarkData, { ...payload, sendId, taskId });
      if (res.success) {
        callback(true);
        const resAgin = yield call(getRemarkData, { sendId, busiId });
        if (resAgin.success) {
          yield put({
            type: 'remarkData',
            payload: resAgin.data,
          });
        } else {
          message.warning(res.message);
        }
      } else {
        message.warning(res.message);
      }
    },
    *getSingle({ payload }, { call, put }) {
      const res = yield call(getSingleData, payload);
      if (res.success) {
        yield put({
          type: 'getSingleData',
          payload: res.data,
        });
      } else {
        message.warning(res.message);
      }
    },
    // 检查是否设置了默认大库
    *fetchSuppList({ payload }, { call, put }) {
      const res = yield call(getSuppList, payload);
      if (res.success) {
        yield put({
          type: 'getSuppList',
          payload: res.data,
        });
      } else {
        message.warning(res.message);
      }
    },
    // 列表的字典
    *fetchDictList({ payload }, { call, put }) {
      const res = yield call(getDictList, payload);
      if (res.success) {
        yield put({
          type: 'getDictList',
          payload: res.data,
        });
      } else {
        message.warning(res.message);
      }
    },
    // 列表查询
    *fetchList({ payload }, { call, put }) {
      const response = yield call(getAddEmpAccuList, payload);
      const { currentPage, pageSizes } = payload;
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSizes,
          },
        });
      } else {
        message.warning(response.message);
      }
    },
    // 获取问题人员列表
    *fetchProList({ payload }, { call, put }) {
      const response = yield call(getAddEmpAccuProList, payload);
      const {
        pagerArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSizes: pageSize,
          },
        });
      } else {
        message.warning(response.message);
      }
    },
    // zj 获取问题人员详情
    *fetchCancelProbFlag({ payload }, { call }) {
      const res = yield call(cancelProbFlag, payload);
      return res;
    },
    *fetchInsertProbFdbk({ payload }, { call }) {
      const res = yield call(insertProbFdbk, payload);
      return res;
    },
    *fetchProblemGet({ payload }, { call, put }) {
      const res = yield call(problemGet, payload);
      if (res.success) {
        yield put({
          type: 'upDate',
          payload: {
            proInfo: res.data,
            probFbdks: res.data.probFdbks,
            addDetId: res.data.busiId,
          },
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    // 上传文件:批量进度
    uploadFileWithProgress:[
      function* ({ payload }, { call, put }) {
        const { tag, formData } = payload;
        let api;
        if (tag === 'bm') {
          api = bmUploadFile;
        } else {
          api = pUploadFile;
        }
        typeName = 'batch';
        const response = yield call(api, formData);
        if (response.success) {
          if (response.data && response.data.successProp !== 100) {
            const { batchId } = response.data;
            const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

            yield put.resolve({
              type: `socket/${SocketActions.subSocketChannel}`,
              payload: {
                batchTask,
              },
            });
          } else {
            yield put({
              type: 'updateBatchTask',
              payload: response.data,
            });
          }
        } else {
          // 上传失败
          message.warning(`${response.message || '上传失败'}`);
        }
        return response;
    },
    {type:'throttle',ms:10000}
  ],
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s.addempaccu);
      let { showProgress, resultInfo, currentStep } = state;
      showProgress = true;
      if (payload.successProp >= 100) {
        resultInfo.errorParams = {
          batNo: payload.batchId,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },
    // 更新首页批量任务数据
    *updateIndexBatchTask({ payload }, { put, select }) {
      const { current, pageSize } = yield select(state => state.addempaccu.pageData.pagination);
      const { copyAll, activeKey } = yield select(state => state.addempaccu);
      if (payload.successProp === 100) {
        const pagerArg = { currentPage: current, pageSize };
        if (Number(activeKey) === 5) {
          yield put({
            type: 'fetchProList',
            payload: {
              ...copyAll,
              pagerArg,
              busiType: 1,
            },
          });
        } else {
          yield put({
            type: 'fetchList',
            payload: {
              ...copyAll,
              currentPage: current,
              pageSizes: pageSize,
            },
          });
        }
         // 先更新进度
      try {
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
          },
        });
        yield delay(3000);
      } catch (e) {
        console.error(e);
      }

        if (payload.errorCount > 0) {
          Modal.warning({
            title: (
              <Row>
                <Row>
                  当前存在<span className="emphasize-text">{payload.errorCount}条</span>
                  数据不可申报，请下载查看。
                </Row>
                <a
                  onClick={() =>
                    downloadFile(
                      { batNo: payload.batchId },
                      '/osApi/accuAddDet/syncAccuAddDeclErrMessage',
                      'POST'
                    )
                  }
                >
                  下载
                </a>
              </Row>
            ),
            okText: '关闭',
            okType: 'default',
            autoFocusButton: 'cancel',
          });
        } else {
          message.success('操作成功！');
        }
        yield put({
          type: 'updateModelData',
          payload: {
            showProgress: false,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload,
        });
      }
    },
  },

  reducers: {
    updateQuery(state, { payload }) {
      return {
        ...state,
        batchQuery: { ...state.batchQuery, ...payload },
      };
    },
    updateArea(state, { payload }) {
      return {
        ...state,
        result: payload,
      };
    },
    updateDeclList(state, { payload }) {
      return {
        ...state,
        declData: payload,
      };
    },
    getDetail(state, { payload }) {
      return {
        ...state,
        detail: { ...state.detail, ...payload.data },
      };
    },
    upDate(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    updateData(state, { payload }) {
      const { beginDateYM, addTypeName, declareAccoName } = payload;
      const { insIdeName } = payload;
      return {
        ...state,
        detail: {
          ...state.detail,
          persion: { ...state.detail.persion, beginDateYM, addTypeName, declareAccoName },
          sendInfoDetDto: { ...state.detail.sendInfoDetDto, insIdeName },
        },
      };
    },
    getSingleData(state, { payload }) {
      return {
        ...state,
        singleInfo: payload,
      };
    },
    remarkData(state, { payload }) {
      const accuRemarks = payload;

      return {
        ...state,
        detail: { ...state.detail, accuRemarks },
      };
    },
    getDictData(state, { payload }) {
      return {
        ...state,
        dictData: { ...state.dictData, ...payload.data },
      };
    },
    getInsInfor(state, { payload }) {
      return {
        ...state,
        insData: payload.data,
      };
    },
    getRemarkData(state, { payload }) {
      return {
        ...state,
        remarkData: payload.data,
      };
    },
    getSuppList(state, { payload }) {
      console.log(payload,'payload');
      console.log(payload.success,'payload.success');
      console.log(!payload.success,'!payload.success');
      return {
        ...state,
        defaultLibrary: !payload.success,
      };
    },
    getDictList(state, { payload }) {
      return {
        ...state,
        execStateList: payload.execStateList,
        payWayList: payload.payWayList,
        curMthDeclFlagList: payload.curMthDeclFlagList,
        matStateList: payload.matStateList,
        declWayList: payload.declWayList,
      };
    },
    getList(
      state,
      {
        payload: { data, currentPage, pageSizes },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      list.map(item => {
        if (item.accuEmpOrd) {
          const tempItem = item;
          tempItem.matState = item.accuEmpOrd.matState;
          tempItem.certNo = item.accuEmpOrd.certNo;
          tempItem.empName = item.accuEmpOrd.empName;
          tempItem.custName = item.accuEmpOrd.custName;
          tempItem.ordSndrName = item.accuEmpOrd.ordSndrName;
          tempItem.sendId = item.accuEmpOrd.sendId;
        }
        return true;
      });
      return {
        ...state,
        pageData: {
          list,
          pagination: {
            total: data.totalCount,
            current: currentPage,
            pageSizes,
            pageSize: pageSizes,
          },
        },
      };
    },
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      // let { showProgress, resultInfo, currentStep } = state;
      if (typeName) {
        // showProgress = true;
        // if (payload.successProp === 100) {
        //   resultInfo.errorParams = {
        //     batNo: payload.batchId,
        //   };
        //   resultInfo = { ...resultInfo, ...payload };
        //   currentStep += 1;
        //   showProgress = false;
        // }
        return {
          ...state,
          ...payload,
          // showProgress,
          // progressPercent: payload.progressPercent,
          // resultInfo,
          // currentStep,
        };
      }
      return { ...state, ...payload };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              if (typeName === 'index') {
                dispatch({
                  type: 'matchBatchId',
                  payload: action.data,
                });
              } else {
                // dispatch({
                //   type: 'updateBatchTask',
                //   payload: action.data,
                // });
                await dispatch({
                  type: 'handleBatchTask',
                  payload: action.data,
                });
              }

              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });

              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
};
